/*
 * Basic no frills app which integrates the ZBar barcode scanner with
 * the camera.
 * 
 * Created by lisah0 on 2012-02-24
 */
package com.ray.scan;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import com.ray.scan.CameraPreview;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
/* Import ZBar Class files */
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;

public class CameraTestActivity extends Activity implements OnClickListener{
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    private DrawImageView mDraw;
    private FrameLayout preview;
    
    private int autoTime = 1000;    // 扫描时间间隔，sdk默认是1000毫秒

    private ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;
    
    private WindowManager wm;
    private int width;
    private int height;
    private int centerX;
    private int centerY;
    
    private int mSpe;   // 校准框半径
    private int mScanModel;    // 当前扫描模式
    
    // 模式显示
    private ImageView qrImage;
    private TextView qrText;
    private ImageView photoImage;
    private TextView photoText;
    
    // 是否已经拍照，保存一张照片
    private boolean isPhoto = true;
    
    private Long lastScanTime = 0L;    // 上次发送二维码的时间
    private Long currentScanTime = 0L;    // 本次扫描时间
    private String currentQrCode = "";    // 本次扫描的二维码
    private String lastQrCode = "";    // 上次发送的二维码
    private final static int SPACE_TIME = 5000;    // 当前二维码和上一次二维码值一样时重新扫描间隔时间
    
    private BeepManager beep;
    
    private ImageButton right;
    
    private static SharedPreferences sharedPreferences;
    private Editor editor;

    static {
        System.loadLibrary("iconv");
    } 

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        sharedPreferences = getSharedPreferences("scan", 
                Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        if(sharedPreferences.getString("flash_status", "").equals("")){
            editor.putString("flash_status", Parameters.FLASH_MODE_TORCH);
            editor.commit(); 
        }
        if(sharedPreferences.getString("ip", "").equals("")){
            editor.putString("ip", Url.IP_ADDRESS);
            editor.commit(); 
        }
        if(sharedPreferences.getString("program", "").equals("")){
            editor.putString("program", Url.PROGRAM_NAME);
            editor.commit(); 
        }

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);
        
        wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        
//        qrImage = (ImageView) findViewById(R.id.qrImage);
//        qrText = (TextView) findViewById(R.id.qrText);
//        photoImage = (ImageView) findViewById(R.id.photoImage);
//        photoText = (TextView) findViewById(R.id.photoText);
        
        right = (ImageButton) findViewById(R.id.right);
        right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(CameraTestActivity.this, Setting.class));
            }
        });
        
//        qrImage.setOnClickListener(this);
//        photoImage.setOnClickListener(this);
//        setScanModel(DrawImageView.DRAW_QR_CORD);    // 默认使用二维码扫描校准框

//        scanButton.setOnClickListener(new OnClickListener() {
//                public void onClick(View v) {
//                    if (barcodeScanned) {
//                        barcodeScanned = false;
//                        scanText.setText("Scanning...");
//                        mCamera.setPreviewCallback(previewCb);
//                        mCamera.startPreview();
//                        previewing = true;
//                        mCamera.autoFocus(autoFocusCB);
//                    }
//                }
//            });
        
        beep = new BeepManager(CameraTestActivity.this);
    }
    
    /**
     * 设置扫描模式
     * @param scanModel
     */
    private void setScanModel(int scanModel){
        mScanModel = scanModel;
        mSpe = width / scanModel;  // 默认使用二维码扫描校准框
        // 恢复默认显示
        qrImage.setImageResource(R.drawable.scan_model_qr);
        qrText.setTextColor(Color.WHITE);
        photoImage.setImageResource(R.drawable.scan_model_photo);
        photoText.setTextColor(Color.WHITE);
        // 设置显示
        if(mScanModel == DrawImageView.DRAW_QR_CORD){
            qrImage.setImageResource(R.drawable.scan_model_qr_pressed);
            qrText.setTextColor(Color.GREEN);
        }else if(mScanModel == DrawImageView.DRAW_TAKE_ICON){
            photoImage.setImageResource(R.drawable.scan_model_photo_pressed);
            photoText.setTextColor(Color.GREEN);
        }
        if(mDraw != null && preview != null){
            preview.removeView(mDraw);
        }
        
        mDraw = new DrawImageView(CameraTestActivity.this, width, 
              (height - 100), mSpe);
        centerX = (width / 2);
        centerY = (height / 2);
        if(preview != null){
            preview.addView(mDraw);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        releaseCamera();
        super.onStop();
    }

    public void onPause() {
//        releaseCamera();
        super.onPause();
    }
    
    public void onDestroy(){
        super.onDestroy();
//        releaseCamera();
    }
    
    public void onResume(){
        if(mCamera == null){
            mCamera = getCameraInstance();
            mPreview = new CameraPreview(CameraTestActivity.this, mCamera, previewCb, autoFocusCB);
            preview.addView(mPreview);
        }
        super.onResume();
    }
    

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
            if(sharedPreferences.getString("flash_status", "").equals(Parameters.FLASH_MODE_TORCH)){
            Camera.Parameters parameters  = c.getParameters();
//            parameters.setPreviewFrameRate(3);//每秒3帧  每秒从摄像头里面获得3个画面  
//            parameters.setPictureFormat(PixelFormat.JPEG);//设置照片输出的格式 
            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);    // 打开闪光灯
//            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);    // 关闭闪光灯
            c.setParameters(parameters);
        }
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
//                if(mScanModel == DrawImageView.DRAW_QR_CORD){
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);
                
                if (result != 0) {
//                    previewing = false;
//                    mCamera.setPreviewCallback(null);
//                    mCamera.stopPreview();
                    
                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {
                        System.out.println("----sym.getType()----" + sym.getType());
                        System.out.println("----sym.getData()----" + sym.getData());
                        barcodeScanned = true;
                        
                        // 判断是否给后台发布信息
                        currentScanTime = System.currentTimeMillis();
                        currentQrCode = sym.getData();
                        if(!currentQrCode.equals(lastQrCode)
                                || (currentScanTime - lastScanTime) > SPACE_TIME){
                            System.out.println("---------扫描成功");
                            VibratorUtil.Vibrate(CameraTestActivity.this, 100);   //震动100ms
                            beep.playBeepSound();
                            lastQrCode = currentQrCode;
                            lastScanTime = currentScanTime;
                            
                            // 向后台发送数据
                            String empNo = "";
                            try {
                                JSONObject object = new JSONObject(lastQrCode);
                                empNo = object.getString("EmpNo");
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            postString(empNo);
                        }
                    }
                    
//                    previewing = true;
//                    mCamera.setPreviewCallback(previewCb);
//                    mCamera.startPreview();
//                    mCamera.autoFocus(autoFocusCB);
//                }
//                }else if(mScanModel == DrawImageView.DRAW_TAKE_ICON
//                        && isPhoto){
//                    /*isPhoto = false;
//                    mCamera.startPreview();
//                    previewing = false;*/
//
//                    Camera.Parameters parameters = camera.getParameters();
//                    int imageFormat = parameters.getPreviewFormat();
//                    Log.i("map", "Image Format: " + imageFormat);
//                    Log.i("CameraPreviewCallback", "data length:" + data.length);
//                    if (imageFormat == ImageFormat.NV21){
//                        // get full picture
//                        Bitmap image = null;
//                        int w = parameters.getPreviewSize().width;
//                        int h = parameters.getPreviewSize().height;
//                        
//                        Rect rect = new Rect(0, 0, w, h); 
//                        YuvImage img = new YuvImage(data, ImageFormat.NV21, w, h, null);
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                        if (img.compressToJpeg(rect, 100, baos)){ 
//                            image =  BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
//
//                            //设置FOCUS_MODE_CONTINUOUS_VIDEO)之后，myParam.set("rotation", 90)失效。图片竟然不能旋转了，故这里要旋转下
//                            Matrix matrix = new Matrix();
//                            matrix.postRotate((float)90.0);
//                            Bitmap rotaBitmap = Bitmap.createBitmap(image, 0, 0, 
//                                    img.getWidth(), img.getHeight(), matrix, false);
//                            
//                            //旋转后rotaBitmap是960×1280.预览surfaview的大小是540×800
//                            //将960×1280缩放到540×800手机分辨率尺寸
//                            Bitmap sizeBitmap = Bitmap.createScaledBitmap(rotaBitmap, width, height, true);
//                            Bitmap rectBitmap = Bitmap.createBitmap(sizeBitmap, 
//                                    (centerX - mSpe), (centerY - mSpe), (mSpe * 2), (mSpe * 2));   // 裁剪相片
//                            isPhoto = false;
//                            VibratorUtil.Vibrate(CameraTestActivity.this, 100);   //震动100ms 
//                            saveJpeg(rectBitmap);    // 保存照片
//                        }
//                    }
                }
            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, autoTime);
            }
        };
        
    public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
    
    public Bitmap renderCroppedGreyscaleBitmap(byte [] yuvData) {
        int width = 240;
        int height = 240;
        int[] pixels = new int[width * height];
        byte[] yuv = yuvData;
        int inputOffset = 0 * 320 + 40;

        for (int y = 0; y < height; y++) {
          int outputOffset = y * width;
          for (int x = 0; x < width; x++) {
            int grey = yuv[inputOffset + x] & 0xff;
            pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
          }
          inputOffset += 320;
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
      }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.qrImage:
            setScanModel(DrawImageView.DRAW_QR_CORD);
            break;
        case R.id.photoImage:
            setScanModel(DrawImageView.DRAW_TAKE_ICON);
            break;

        default:
            break;
        }
    }
    /*给定一个Bitmap，进行保存*/
    public void saveJpeg(Bitmap bm){
        String savePath = "/mnt/sdcard/zbar/";
        File folder = new File(savePath);
        if(!folder.exists()) //如果文件夹不存在则创建
        {
            folder.mkdir();
        }
        long dataTake = System.currentTimeMillis();
        String jpegName = savePath + dataTake +".jpg";
        Log.i("ZBAR", "saveJpeg:jpegName--" + jpegName);
        //File jpegFile = new File(jpegName);
        try {
            FileOutputStream fout = new FileOutputStream(jpegName);
            BufferedOutputStream bos = new BufferedOutputStream(fout);
            //          //如果需要改变大小(默认的是宽960×高1280),如改成宽600×高800
            //          Bitmap newBM = bm.createScaledBitmap(bm, 600, 800, false);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            
            bos.flush();
            bos.close();
            Log.i("ZBAR", "saveJpeg：存储完毕！");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.i("ZBAR", "saveJpeg:存储失败！");
            e.printStackTrace();
        }
    }
    
    public void postString(final String qrCode){
        new AsyncTask<Void, Void, String>(){
            protected void onPreExecute() {
            };
            @Override
            protected String doInBackground(Void... params) {
                String result = null;
                try {
                    long start = System.currentTimeMillis();
                    result = Util.postStr(CameraTestActivity.this,
                            Url.HEAD + sharedPreferences.getString("ip", "")
                            + sharedPreferences.getString("program", "") + Url.POST_QR_CODE, 
                            qrCode);    // 上传
                    long end = System.currentTimeMillis();
                    long cost = end - start;
                    if (cost < 2000) {
                        try {
                            Thread.currentThread().sleep(2000 - cost);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
            
            protected void onPostExecute(String result) {
                System.out.println("----result-----" + result);
                // 后续处理
                if(!result.equals("success")){
                    Toast.makeText(CameraTestActivity.this, "网络错误码=" + result,
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(CameraTestActivity.this, "服务器返回结果=" + result,
                            Toast.LENGTH_SHORT).show();
                }
            };
        }.execute();
    }
}
